package com.shelpe.services.scheduler.item.product;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.SkipListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import com.shelpe.services.scheduler.mongorepository.SyncPerDayRecordRepository;
import com.shelpe.services.scheduler.po.SyncLog;
import com.shelpe.services.scheduler.po.SyncPerDayRecord;
import com.shelpe.services.scheduler.po.Users;
import com.shelpe.services.scheduler.repository.SyncLogRepository;
import com.shelpe.services.scheduler.util.Util;

@Component("productSkipListener")
public class ProductSkipListener  implements SkipListener<Users, SyncLog>{

	private static final Logger logger = LoggerFactory.getLogger(ProductSkipListener.class);
	
	@Autowired 
	private SyncLogRepository syncLogRep;
	
	@Autowired
	private JavaMailSender mailSender;
	
	@Autowired
	private SyncPerDayRecordRepository recordRep;
	
	@Override
	public void onSkipInRead(Throwable t) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSkipInWrite(SyncLog item, Throwable t) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSkipInProcess(Users item, Throwable t) {
		// TODO Auto-generated method stub
		logger.info(">>>ProductSkipListener, error: {}", t);
		saveAndCheckEmail("ProductSkip", 98);

		SyncLog log = new SyncLog();
		Util.buildExceptionSyncLog(log, item.getUserId(), "syncProduct", t);
		syncLogRep.save(log);
	}
	
	private void saveAndCheckEmail(String skipName, int limit){
		
		SyncPerDayRecord record = recordRep.findOne(skipName);
		if(record == null){
			record = new SyncPerDayRecord();
			record.setFailedNum(1);
			record.setProcessName(skipName);
			record.setMessage("skip process num");
		}
			
		int num = record.getFailedNum() + 1;	
		record.setFailedNum(num);
		if(num > limit){
			try{
				 SimpleMailMessage message = new SimpleMailMessage();
		         
				 message.setFrom("15868865221@163.com");      
				 message.setTo("wuya@shelpe.com");   
				 message.setSubject("[simba]Keyword sync warning");	      
				 message.setText("Warning: Today, Keyword sync failed too many!");    
				 mailSender.send(message);

			}catch(Exception e){
				logger.info("error {}", e);
			}
		}
		
		recordRep.save(record);
	}

}
